<?php

/**
 * Service class for calls on the database
 */

class Database {

	/**
	 * Connect to server and optionally define a database
	 *
	 * @param string $server server IP or domain
	 * @param string $username
	 * @param string $password
	 * @param string $database name of database
	 * @return $link
	 */
	public static function connect($server, $username, $password, $database = "") {
		
        // Use of the @mysql_connect suppresses echo of error message which would expose name and path of file containing mysql_connect call
		//no need to connect to same db-server  again, just select db
        $link = @mysql_connect($server, $username, $password); 
        //$link = true;
        
		if ($link) {
			mysql_query("SET NAMES 'utf8'");
			if (strlen($database) > 0) {
				mysql_select_db($database);
               if (strlen(mysql_error()) > 0) {
					return("Database error");
				}
			}
		}
		return $link;
	}

	
	/**
	 * Open persistent connection to server and optionally define a database
	 *
	 * @param string $server server IP or domain
	 * @param string $username
	 * @param string $password
	 * @return $link
	 */
	public static function pconnect($server, $username, $password) {
		// Use of the @mysql_connect suppresses echo of error message which would expose name and path of file containing mysql_connect call
		$link = @mysql_pconnect($server, $username, $password);
		if ($link) {
			mysql_query("SET NAMES 'utf8'");
		}
		return $link;
	}

	/**
	 * Select current database
	 *
	 * @param string $database name of database
	 */
	public static function selectDatabase($database = "", $link) {
		if (strlen($database) > 0) {
			mysql_select_db($database, $link);
			if (strlen(mysql_error()) > 0) {
				return("Database error");
			}
		} else {
			return("Database error");			
		}
		return "";
	}

	/**
 	 * TODO - test no connection condition
 	 * Run a simple non-transactional insert query and return an error message or the value of
 	 * mysql_insert_id()
 	 *
 	 * @param $query the query string
 	 * @return an error string or the id of an inserted record
 	 */
	public static function runInsertQuery($query) {
		mysql_query($query);
		if (strlen(mysql_error()) > 0) {
			// Do not expose details of the error to users
			error_log(mysql_error());
			return "Database error";
		}
		return mysql_insert_id();
	}

	/**
 	 * Run a simple non-transactional select query and return either data or an error message
 	 *
 	 * @param $query the query string
 	 * @return a result set or an error message
 	 */
	public static function runSelectQuery($query, $resultType = MYSQL_NUM) {
		$data = array();
		$result = mysql_query($query);
		if (strlen(mysql_error()) > 0) {
			// Do not expose details of the error to users
			error_log(mysql_error());
			return "Database error";
		}
		if ($result == FALSE || mysql_num_rows($result)== 0) {
			return $data;
		}
		while ($line = mysql_fetch_array($result, $resultType)) {
			$count = sizeOf($line);
			if ($resultType == MYSQL_NUM) {
				for ($i=0;$i<$count;$i++) {
					//if ($_SESSION[Session::$KEY_LANGUAGE] != Configuration::$APP_DEFAULT_LANGUAGE_CODE) $line[$i] = iconv(Configuration::$APP_CHARSET_ISO,Configuration::$APP_CHARSET_UTF_8, $line[$i]);
				}
			}
			if ($resultType == MYSQL_ASSOC) {
				if ($count > 0) {
					foreach($line as $lineElement) {
						//if ($_SESSION[Session::$KEY_LANGUAGE] != Configuration::$APP_DEFAULT_LANGUAGE_CODE) $lineElement = iconv(Configuration::$APP_CHARSET_ISO,Configuration::$APP_CHARSET_UTF_8, $lineElement);						
					}
				}
			}
			array_push($data, $line);
		}
		return $data;
	}

	/**
 	 * General query with no data returned but with need to check for errors
 	 * 
 	 * @param $query the query string
 	 * @return an empty string meaning everything was OK or a string containing an error message
   */
	public static function runQuery($query) {
		mysql_query($query);
		if (strlen(mysql_error()) > 0) {
			// Do not expose details of the error to users
			error_log(mysql_error());
			return "Database error";
		}
		return "";
	}

	/**
   * Run a simple non-transactional update query and return either an empty string or an error message
 	 *
 	 * @deprecated use runQuery
 	 * @param $query the query string
 	 * @return an empty string meaning everything was OK or a string containing an error message
 	 */
	public static function runUpdateQuery($query) {
		mysql_query($query);
		if (strlen(mysql_error()) > 0) {
			// Do not expose details of the error to users
			error_log(mysql_error());
			return "Database error";
		}
		return "";
	}
	
	public static function insert_array($table, $data) {
	      // Inserts a row into the database from key->value pairs in an array. The
	      // array passed in $data must have keys for the table's columns. You can
	      // not use any MySQL functions with string and date types with this 
	      // function.  You must use insert_sql for that purpose.
	      // Returns the id of the insert or true if there is not auto_increment
	      // column in the table.  Returns false if there is an error.
	      $update=array();
	      if (empty($data)) { 
	         return false;
	      }
	      
	      $cols = '(';
	      $values = '(';
	      foreach ($data as $key=>$value) {     // iterate values to input
	         $cols .= "`$key`,";  
	         $value = self::check_input($value); // addslashes($value);
			 $update[]="`$key`=VALUES(`$key`)";
	         $values .= "$value,";
	      }
	      $cols = rtrim($cols, ',').')';
	      $values = rtrim($values, ',').')';     
	
	      // insert values
	      $sql = "INSERT INTO `".$table."` $cols VALUES $values ON DUPLICATE KEY UPDATE ".implode(",",$update);
	      return self::insert_sql($sql);
      
   }
   
   public static function insertArray($table, $data) {
	      // Inserts a row into the database from key->value pairs in an array. The
	      // array passed in $data must have keys for the table's columns. You can
	      // not use any MySQL functions with string and date types with this 
	      // function.  You must use insert_sql for that purpose.
	      // Returns the id of the insert or true if there is not auto_increment
	      // column in the table.  Returns false if there is an error.
	      $update=array();
	      if (empty($data)) { 
	         return false;
	      }
	      
	      $cols = '(';
	      $values = '(';
	      foreach ($data as $key=>$value) {     // iterate values to input
	         $cols .= "`$key`,";  
	         $value = self::check_input($value); // addslashes($value);
			 $update[]="`$key`=VALUES(`$key`)";
	         $values .= "$value,";
	      }
	      $cols = rtrim($cols, ',').')';
	      $values = rtrim($values, ',').')';     
	
	      // insert values
	      $sql = "INSERT INTO `".$table."` $cols VALUES $values";
	      return self::insert_sql($sql);
      
   }
 	public static function insert_sql($sql) {
	      // Inserts data in the database via SQL query.
	      // Returns the id of the insert or true if there is not auto_increment
	      // column in the table.  Returns false if there is an error.     
	      $r = mysql_query($sql);
	      if (!$r) {
	         return false;
	      }
	    
	      $id = mysql_insert_id();
	      if ($id == 0) return true;
	      else return $id; 
   	}
   
	public static function update_array($table, $data, $condition) {
	      // Updates a row into the database from key->value pairs in an array. The
	      // array passed in $data must have keys for the table's columns. You can
	      // not use any MySQL functions with string and date types with this 
	      // function.  You must use insert_sql for that purpose.
	      // $condition is basically a WHERE claus (without the WHERE). For example,
	      // "column=value AND column2='another value'" would be a condition.
	      // Returns the number or row affected or true if no rows needed the update.
	      // Returns false if there is an error.
	      
	      if (empty($data)) {
	         return false;
	      }
	      
	      $sql = "UPDATE `$table` SET";
	      foreach ($data as $key=>$value) {     // iterate values to input
	          
	         $sql .= " $key=";  
	         
	         //$col_type = $this->get_column_type($table, $key);  // get column type
	         //if (!$col_type) return false;  // error!
	         
	         $value = self::check_input($value); // addslashes($value);
	         $value = "$value,";
	         $sql.=$value;	
	
	      }
	   		
	      $sql = rtrim($sql, ','); // strip off last "extra" comma
	      
	      if (!empty($condition)) $sql .= " WHERE $condition";
	      // insert values
	      return self::update_sql($sql);
  	}
   
  	public static function update_sql($sql) {
	      // Updates data in the database via SQL query.
	      // Returns the number or row affected or true if no rows needed the update.
	      // Returns false if there is an error.
  		$r = mysql_query($sql);
	      if (!$r) {
	         return false;
	      }
	  
	      $rows = mysql_affected_rows();
	      if ($rows == 0) return true;  // no rows were updated
	      else return $rows;
   	}
   	
	function check_input($value)
	{
		// Stripslashes
  		$value = stripslashes($value);
  
		// Quote if not a number
  		$value = "'" . mysql_real_escape_string($value) . "'";
 
		return $value;	
	}
	
	//Insert a two dimensional array  into the db
	public static function insertMultiArray($values,$table){
		$sql="INSERT INTO $table (`";
		$count=0;
		foreach($values as $value){
			if($count==0){
				$sql.=implode("`,`",array_keys( $value ));
				$sql.="`) VALUES ( ";
			}
			$count++;
			foreach($value as $key=>$element)
  				$value[$key]= self::check_input($element);
  			$sql.=implode(",",$value);
			$sql.=" )";
			if($count<count($values))
				$sql.=",(";
		}
		return Database::runQuery($sql);
	}
}
?>
